package com.yx.learn.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sun.rowset.internal.Row;
import com.yx.learn.domain.Department;
import com.yx.learn.domain.Position;
import com.yx.learn.domain.User;
import com.yx.learn.service.DepartmentService;
import com.yx.learn.service.PositionService;
import com.yx.learn.service.UserService;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionid = 1L;

	

	HttpServletRequest request = ServletActionContext.getRequest();
	HttpSession session = request.getSession();

	private int id;
	private String ids;
	private String employNo;
	private String employName;
	private String password;
	private String passwordOld;
	private String repassword;
	private String sex;
	private String birthday;
	private String telephone;
	private String email;
	private String address;
	private String photoUrl;
	private Timestamp createTime;
	private String timeForm;
	private String timeTo;

	private int page;// 当前页

	private int rows;// 页面大小

	private int positionID;// 职位id

	private int departmentID;// 部门id
	
	@Resource
	private UserService userService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private PositionService positionService;

	// 增加用户

	public void saveUser() {
		try {
			System.out.println("departmentID="+departmentID);
			User user = new User();
			user.setEmployNo(employNo);
			user.setEmployName(employName);
			user.setPassword(password);
			user.setSex(sex);
			user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
			user.setTelephone(telephone);
			user.setEmail(email);
			user.setAddress(address);
			user.setPhotoUrl(photoUrl);
			user.setCreateTime(new Date());
			user.setDepartment(departmentService.findById(departmentID));
			user.setPosition(positionService.findById(positionID));

			userService.saveUser(user);
			this.toResponse("{\"status\":\"ok\" , \"message\":\"添加用户成功!\"}");
			System.out.println("添加新了用户");

		} catch (Exception e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
			// this.toResponse("{\"status\":\"fail\" , \"message\":\"添加用户失败!\"}");

			System.out.println("添加用户失败");
		}
	}

	// 删除多个用户

	public void deleteUsers() {

		try {
			String[] uid = ids.split(",");
			for (int i = 0; i < uid.length; i++) {
				id = Integer.parseInt(uid[i]);
				userService.deleteUser(userService.findById(id));
			}
			this.toResponse("ok");
			// this.toResponse("{\"status\":\"ok\" , \"message\":\"删除用户成功!\"}");
			System.out.println("删除用户");
		} catch (Exception e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
			this.toResponse("fail");
			// this.toResponse("{\"status\":\"fail\" , \"message\":\"删除用户失败!\"}");

			System.out.println("删除用户失败");

		}

	}

	// 修改用户

	public void updateUser() {

		try {
			User user = userService.findById(id);
			user.setEmployNo(employNo);
			user.setEmployName(employName);
			user.setPassword(password);
			user.setSex(sex);
			user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
			user.setTelephone(telephone);
			user.setEmail(email);
			user.setAddress(address);
			user.setPhotoUrl(photoUrl);
			user.getDepartment().setId(departmentID);
			user.getPosition().setId(positionID);
			userService.updateUser(user);
			this.toResponse("{\"status\":\"ok\" , \"message\":\"修改用户成功!\"}");
			System.out.println("修改用户信息成功");

		} catch (Exception e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
			// this.toResponse("{\"status\":\"fail\" , \"message\":\"修改用户失败!\"}");

			System.out.println("修改用户信息失败");
		}

	}

	// 修改个人

	public void updateUserPSN() {

		try {
			System.out.println("psn：" + id);
			User user = userService.findById(id);
			user.setEmployName(employName);
			user.setTelephone(telephone);
			user.setEmail(email);
			userService.updateUser(user);
			session.setAttribute("user", user);
			this.toResponse("ok");
			// this.toResponse("{\"status\":\"ok\" , \"message\":\"修改个人信息成功!\"}");

			System.out.println("修改个人信息成功");

		} catch (Exception e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
			this.toResponse("fail");
			// this.toResponse("{\"status\":\"fail\" , \"message\":\"修改个人信息失败!\"}");

			System.out.println("修改个人信息失败");

		}

	}

	// 修改个人密码

	public void userUpdatePwd() {

		User user = (User) session.getAttribute("user");
		String passwordNow = user.getPassword();
		if (passwordNow.equals(passwordOld) && password.equals(repassword)) {
			try {
				user.setPassword(password);
				userService.updateUser(user);
				session.setAttribute("user", user);
				this.toResponse("ok");
				// this.toResponse("{\"status\":\"ok\" , \"message\":\"修改密码成功!\"}");

				System.out.println("修改密码成功");

			} catch (Exception e) {
				// TODO Auto-generated catch block

				e.printStackTrace();
				this.toResponse("fail");
				// this.toResponse("{\"status\":\"fail\" , \"message\":\"修改密码失败!\"}");

			}
		} else {
			// this.toResponse("{\"status\":\"fail\" , \"message\":\"原密码错误或者新密码不一致!\"}");

			this.toResponse("fail");
			System.out.println("原密码错误或者新密码不一致");

		}

	}

	// 显示所有用户

	public void findUsers() {

		try {
			StringBuffer sb = new StringBuffer();
			sb.append("From User where 1=1 ");
			if (employNo != null && !employNo.equals("")) {
				sb.append("and employNo = '").append(employNo).append("'");
			}
			if (employName != null && !employName.equals("")) {
				sb.append("and employName = '").append(employName).append("'");
			}
			if (timeForm != null && !timeForm.equals("")) {
				sb.append("and createTime >= '").append(timeForm).append("'");
			}
			if (timeTo != null && !timeTo.equals("")) {
				sb.append("and createTime <= '").append(timeTo).append("'");
			}
			sb.append(" order by createTime desc");
			String hql = sb.toString();
			System.out.println("hql=" + hql);
			List<User> users = userService.findUsers(hql, page, rows);
			String json = "";
			if (users != null) {
				JSONArray ja = new JSONArray();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				int total = userService.findRows(hql);
				System.out.println(users.size() + "total: " + total);
				for (User user : users) {
					JSONObject jo = new JSONObject();// auth 的孩子打包 为jo
					jo.put("id", user.getId());
					jo.put("employNo", user.getEmployNo());
					jo.put("employName", user.getEmployName());
					jo.put("password", user.getPassword());
					jo.put("sex", user.getSex());
					jo.put("birthday", sdf.format(user.getBirthday()));
					jo.put("telephone", user.getTelephone());
					jo.put("email", user.getEmail());
					jo.put("address", user.getAddress());
					jo.put("photoUrl", user.getPhotoUrl());
					jo.put("createTime", sdf.format(user.getCreateTime()));
					jo.put("departmentID", user.getDepartment().getId());
					jo.put("deptName", user.getDepartment().getDeptName());
					jo.put("positionID", user.getPosition().getId());
					jo.put("positionName", user.getPosition().getPositionName());
					ja.add(jo);
				}
				json = "{\"total\":" + total + ",\"rows\":" + ja.toString()
						+ "}";
			}
			System.out.println("json=" + json);
			toResponse(json);
			System.out.println("所有用户");

		} catch (Exception e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
			String json = "{\"status\":\"fail\" , \"message\":\"操作失败!\"}";
			toResponse(json);
		}
	}

	// 下拉框数据

	public void usersToCombobox() {
		try {
			String json = userService.usersToCombobox();
			this.toResponse(json);
		} catch (Exception e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		}
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getEmployNo() {
		return employNo;
	}

	public void setEmployNo(String employNo) {
		this.employNo = employNo;
	}

	public String getEmployName() {
		return employName;
	}

	public void setEmployName(String employName) {
		this.employName = employName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPasswordOld() {
		return passwordOld;
	}

	public void setPasswordOld(String passwordOld) {
		this.passwordOld = passwordOld;
	}

	public String getRepassword() {
		return repassword;
	}

	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getPhotoUrl() {
		return photoUrl;
	}

	public void setPhotoUrl(String photoUrl) {
		this.photoUrl = photoUrl;
	}

	public Timestamp getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Timestamp createTime) {
		this.createTime = createTime;
	}

	public String getTimeForm() {
		return timeForm;
	}

	public void setTimeForm(String timeForm) {
		this.timeForm = timeForm;
	}

	public String getTimeTo() {
		return timeTo;
	}

	public void setTimeTo(String timeTo) {
		this.timeTo = timeTo;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getPositionID() {
		return positionID;
	}

	public void setPositionID(int positionID) {
		this.positionID = positionID;
	}

	public int getDepartmentID() {
		return departmentID;
	}

	public void setDepartmentID(int departmentID) {
		this.departmentID = departmentID;
	}

}